package com.api;

import com.portal.admin.base.constant.AdminAppConst;
import com.portal.admin.base.constant.WxAppConst;
import com.portal.admin.base.entity.BaseAction;
import com.portal.admin.base.entity.ResultInfo;
import com.portal.admin.base.entity.UserToken;
import com.portal.admin.role.service.SysRoleService;
import com.portal.admin.userAuthor.entity.UserAuthor;
import com.portal.admin.userAuthor.service.UserAuthorService;
import com.portal.admin.utils.admin.ObjectUtils;
import com.portal.admin.utils.session.SessionUtils;
import com.portal.module.userRegister.entity.UserRegister;
import com.portal.module.userRegister.service.UserRegisterService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.portal.admin.config.service.SysConfigService.getSysConfig;

/**
 * 微信用户登录接口
 */
@RestController
@RequestMapping("/api/login")
public class ApiLoginController extends BaseAction {
    @Autowired
    UserRegisterService userRegisterService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    UserAuthorService userAuthorService;

    /**
     * 获取用户token
     *
     * @param request
     * @param code
     * @return
     */
    @RequestMapping("/getToken")
    public ResultInfo getAppletToken(HttpServletRequest request,String code,int from) {
        try {
            JSONObject result = SessionUtils.getJscode2session(code,from);
            Integer errcode = (Integer) result.get("errcode");
            String errmsg = (String) result.get("errmsg");
            if (errcode == null) {
                Map<String, Object> map = new HashMap();
                //需要执行下前端才能从res.header["Set-Cookie"];获取
                String sessionId = request.getSession().getId();
                Integer timeOut = Integer.valueOf(getSysConfig(WxAppConst.APPLET_TIMEOUT));
                request.getSession().setMaxInactiveInterval(timeOut);//单位:秒
                UserToken userToken = new UserToken();
                userToken.setSessionId(sessionId);
                userToken.setUnionid((String) result.get("unionid"));
                userToken.setOpenid((String) result.get("openid"));
                map.put("userToken", userToken);
                SessionUtils.setToken(userToken);
                return ResultInfo.ok("获取用户凭证信息成功！", map);
            }
            return ResultInfo.error("获取用户信息code无效" + errcode + " 错误信息: " + errmsg);
        } catch (Exception e) {
            return ResultInfo.error("获取用户信息失败，异常信息：" + e.getMessage());
        }
    }
    /**
     * 客户端用户登录
     *
     * @param entity
     * @return
     */
    @RequestMapping("/userLogin")
    public ResultInfo userLogin(UserRegister entity) {
        if (StringUtils.isEmpty(entity.getLoginName())) {
            return ResultInfo.error("登录名不能为空！");
        }
        if (StringUtils.isEmpty(entity.getPassword())) {
            return ResultInfo.error("密码不能为空！");
        }
        UserRegister params = new UserRegister();
        params.setLoginName(entity.getLoginName());
        UserRegister userRegister = userRegisterService.get(params);
        if (userRegister != null) {
            ByteSource salt = ByteSource.Util.bytes(AdminAppConst.SALT);
            String passwordMd5 = new SimpleHash("MD5", entity.getPassword(), ByteSource.Util.bytes(salt), 1024).toString();
            if (!(userRegister.getPassword().equals(passwordMd5))) {//已经被注册过
                return ResultInfo.error("该用户密码不正确！");
            }
            UserRegister userInfo = userRegisterService.get(userRegister.getId());
            //保存信息到session
            SessionUtils.setUserInfo(userInfo);
            return ResultInfo.ok("登录成功");
        } else {
            return ResultInfo.error("该用户不存在！");
        }
    }


    /**
     * 更新用户授权信息
     *
     * @return
     */
    @RequestMapping("/updateUserAuthor")
    public ResultInfo updateUserAuthor(UserAuthor entity) {
        try {
            UserToken token = SessionUtils.getToken();
            if (token == null) {
                return ResultInfo.error("用户凭证不能为空！");
            }
            entity.setUnionid(token.getUnionid());
            entity.setOpenid(token.getOpenid());
            UserAuthor params = new UserAuthor();
            params.setOpenid(entity.getOpenid());
            UserAuthor userAuthor = userAuthorService.get(params);
            if (userAuthor == null) {
                userAuthorService.insert(entity);
            } else {
                entity.setId(userAuthor.getId());
                userAuthorService.update(entity);
            } //保存session
            SessionUtils.setUserAuthor(entity);
            return ResultInfo.ok("更新用户信息成功！", entity);
        } catch (Exception e) {
            return ResultInfo.error("获取用户信息失败，异常信息：" + e.getMessage());
        }
    }

    /**
     * 注册
     * @param entity
     * @return
     */
    @RequestMapping("/register")
    public ResultInfo register(UserRegister entity) {
        //根据登录名判断是否有用户
        if (StringUtils.isEmpty(entity.getLoginName())) {
            return ResultInfo.error("登录名不能为空！");
        }
        if (StringUtils.isEmpty(entity.getPassword())) {
            return ResultInfo.error("密码不能为空！");
        }
        UserRegister params = new UserRegister();
        params.setLoginName(entity.getLoginName());
        UserRegister nameRegister = userRegisterService.get(params);
        if (nameRegister != null) {//已经被注册过
            return ResultInfo.error("注册失败,该登录名已经被注册过");
        }
        ByteSource salt = ByteSource.Util.bytes(AdminAppConst.SALT);
        String passwordMd5 = new SimpleHash("MD5", entity.getPassword(), ByteSource.Util.bytes(salt), 1024).toString();
        entity.setPassword(passwordMd5);
        UserAuthor userAuthor = SessionUtils.getUserAuthor();
        if(ObjectUtils.isNotNull(userAuthor)){
            entity.setUserAuthorId(userAuthor.getId());
            entity.setPhoto(userAuthor.getAvatarUrl());
        }
        userRegisterService.insert(entity);
        return ResultInfo.ok("注册成功！");
    }


    /**
     * 修改密码
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/modifyPsd")
    public ResultInfo modifyPsd(HttpServletRequest request){
        String newPassword = request.getParameter("newPassword");
        String oldPassword = request.getParameter("oldPassword");
        String prePassword = request.getParameter("prePassword");
        if (StringUtils.isEmpty(oldPassword)) {
            return ResultInfo.error("旧密码不能为空！");
        }
        if (StringUtils.isEmpty(newPassword)) {
            return ResultInfo.error("新密码不能为空！");
        }
        if (StringUtils.isEmpty(prePassword)) {
            return ResultInfo.error("确认密码不能为空！");
        }
        if (!newPassword.equals(prePassword)) {
            return ResultInfo.error("两次密码不一致！");
        }
        UserRegister userInfo = SessionUtils.getUserInfo();
        if (userInfo != null) {
            ByteSource salt = ByteSource.Util.bytes(AdminAppConst.SALT);
            String passwordMd5 = new SimpleHash("MD5", oldPassword, ByteSource.Util.bytes(salt), 1024).toString();
            if (!passwordMd5.equals(userInfo.getPassword())) {
                return ResultInfo.error("旧密码错误！");
            } else {
                String passwordNew = new SimpleHash("MD5", prePassword, ByteSource.Util.bytes(salt), 1024).toString();
                userInfo.setPassword(passwordNew);
                userRegisterService.update(userInfo);
                return ResultInfo.ok("密码修改成功！");
            }
        }
        return ResultInfo.ok("密码修改失败！");
    }

    /**
     * 更新用户注册信息
     * 填写或者注册
     * @param userInfo
     * @return
     */
    @RequestMapping("/updateUserInfo")
    public ResultInfo updateRegister(UserRegister userInfo) {
        String currentUserId = SessionUtils.getCurrentUserId();
        if (!StringUtils.isEmpty(currentUserId)) {
            userInfo.setId(currentUserId);
            userRegisterService.update(userInfo);//修改
            SessionUtils.setUserInfo(userInfo);
            return ResultInfo.ok("更新成功！",userInfo);
        }
        return ResultInfo.ok("更新失败！");
    }


    /**
     * 获取登录信息
     *
     * @return
     */
    @RequestMapping("/getLoginInfo")
    public ResultInfo getLoginInfo() {
        Map<String, Object> datas = new HashMap<>();
        UserRegister userInfo = SessionUtils.getUserInfo();
        datas.put("userInfo", userInfo);
        return ResultInfo.ok("获取登录信息成功！", datas);
    }

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping("/getUserInfo")
    public ResultInfo getRegister() {
        String currentUserId = SessionUtils.getCurrentUserId();
        if (!StringUtils.isEmpty(currentUserId)) {
            UserRegister userInfo = userRegisterService.get(currentUserId);
            return ResultInfo.ok("获取成功！", userInfo);
        }
        return ResultInfo.ok("获取失败！");
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/loginOut")
    public ResultInfo loginOut() {
        UserRegister userInfo = SessionUtils.getUserInfo();
        if (userInfo != null) {
            SessionUtils.clearSession();
        }
        return ResultInfo.ok("退出成功！");
    }



}



